/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiruss.efair.servlets;

import com.hiruss.efair.entities.Advertisement;

import com.hiruss.efair.persistence.AdvertisementManager;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Hiru
 */
public class AddAdvertisementServlet extends HttpServlet {

		private String filePath = "G:\\MY_PROJECTS\\NB\\eFairData\\data\\";
		private String tempDirectory = "G:\\MY_PROJECTS\\NB\\eFairData\\temp";
		private int maxFileSize = 5000 * 1024;
		private int maxMemSize = 4 * 1024;
		private File file;
		private int imageCount = 0;
		private boolean datasheetFound = false;

		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
				try {
						long addId = new Date().getTime();
						Advertisement ad = new Advertisement();
						ad.setAddId(addId);

						this.imageCount = 0;
						this.datasheetFound = false;
						if (!ServletFileUpload.isMultipartContent(req)) {
								return;
						}

						DiskFileItemFactory factory = new DiskFileItemFactory();
						// maximum size that will be stored in memory
						factory.setSizeThreshold(maxMemSize);
						File tempDir = new File(tempDirectory);
						if (!tempDir.exists()) {
								tempDir.mkdirs();
						}

						// Location to save data that is larger than maxMemSize.
						factory.setRepository(tempDir);

						// Create a new file upload handler
						ServletFileUpload upload = new ServletFileUpload(factory);
						// maximum file size to be uploaded.
						upload.setSizeMax(maxFileSize);

						// Parse the request to get file items.
						List<FileItem> fileItems = upload.parseRequest(req);

						// Process the uploaded file items
						for (FileItem fi : fileItems) {
								if (!fi.isFormField()) {
										// Get the uploaded file parameters
										String fieldName = fi.getFieldName();
										System.out.println(fieldName);
										String fileName = fi.getName();
										String contentType = fi.getContentType();
										String dataPath = filePath + addId;
										File dir = new File(dataPath);
										if (!dir.exists()) {
												dir.mkdirs();
										}
										// boolean isInMemory = fi.isInMemory();
										long sizeInBytes = fi.getSize();
										// Write the file
										if (fieldName.equalsIgnoreCase("datasheet")
												&& contentType.equalsIgnoreCase("application/pdf")) {
												file = new File(dataPath + "\\"
														+ addId + fileName.substring(fileName.lastIndexOf(".")));
												datasheetFound = true;
												fi.write(file);
										} else if (fieldName.equalsIgnoreCase("images") && contentType.startsWith("image/")) {
												file = new File(dataPath + "\\"
														+ addId + "_" + imageCount + fileName.substring(fileName.lastIndexOf(".")));
												imageCount++;
												fi.write(file);
										}
										System.out.println("Uploaded Filename: " + fileName + " "
												+ "with " + fieldName + " " + fileName + " " + contentType + " " + sizeInBytes);
								} else {
										if (fi.getFieldName().equalsIgnoreCase("sellerName")) {
												ad.setSellerName(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("sellerContactNum")) {
												ad.setSellerContactNum(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("sellerEmail")) {
												ad.setSellerEmail(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("category")) {
												ad.setCategory(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("description")) {
												ad.setDescription(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("item")) {
												ad.setItem(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("price")) {
												ad.setPrice(Double.parseDouble(fi.getString()));
										} else if (fi.getFieldName().equalsIgnoreCase("weight")) {
												ad.setWeight(fi.getString());
										} else if (fi.getFieldName().equalsIgnoreCase("dimensions")) {
												ad.setDimensions(fi.getString());
										}
								}
						}


						ad.setNumOfImages(this.imageCount);

						if (!this.datasheetFound) {
								req.setAttribute("message", "Please attach the datasheet");
								req.getRequestDispatcher("add.jsp").forward(req, resp);
						} else if (this.imageCount < 2) {
								req.setAttribute("message", "Please attach atleast 2 images");
								req.getRequestDispatcher("add.jsp").forward(req, resp);
						} else {
								ad.setPaid(false);
								ad.setApproved(false);
								ad.setPiority(1);
								AdvertisementManager manager = AdvertisementManager.getInstance();
								manager.addAdvertisement(ad);
								req.setAttribute("ad", ad);
								req.getRequestDispatcher("gateway.jsp").forward(req, resp);
						}
				} catch (Exception ex) {
						ex.printStackTrace();
				}
		}
}
